<template>
  <div>
    <!-- 添加按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="width: 90px; margin-bottom: 10px" @click="showDialog">添加</el-button>
    <!-- 表格 -->
    <el-table :data="list" style="width: 100%" border stripe>
      <el-table-column label="序号" width="80" align="center" type="index"> </el-table-column>
      <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
      <el-table-column label="品牌LOGO">
        <!-- 插槽(数据回传 slot-scope="{ row, $index }") -->
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 30%; height: 50%" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="warning" size="small" icon="el-icon-edit" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[3, 5, 10]" :page-size="limit" layout=" prev, pager, next, jumper ,->,sizes,total" :total="total" style="text-align: center"> </el-pagination>
    <!-- 添加和修改的对话框 -->
    <el-dialog :title="tmForm.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
      <el-form :model="tmForm" style="width: 80%" :rules="rules" ref="ruleTmForm">
        <el-form-item label="图片名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="图片LOGO" label-width="114px" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="text-align: left">只能上传jpg文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TradeMark',
  data() {
    return {
      // 当前页数，这里实现持久化数据
      page: Number(sessionStorage.getItem('pager')) || 1,
      // 每页条数
      limit: 3,
      // 总条数
      total: 0,
      // 展示的数据
      list: [],
      // 控制对话框
      dialogFormVisible: false,
      imageUrl: '',
      // 收集表单元素
      tmForm: {
        tmName: '',
        logoUrl: '',
      },
      // 表单验证
      rules: {
        tmName: [
          { required: true, message: '请填写图片名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' },
        ],
        logoUrl: [{ required: true, message: '请选择图片' }],
      },
    }
  },
  mounted() {
    this.getPageList()
  },
  methods: {
    async getPageList(pager = Number(sessionStorage.getItem('pager'))) {
      this.page = pager
      const { page, limit } = this
      let res = await this.$API.TradeMark.reqTradeMarkList(page, limit)
      if (res.code === 200) {
        this.total = res.data.total
        this.list = res.data.records
      }
    },
    async handleCurrentChange(currentPage) {
      this.page = currentPage
      sessionStorage.setItem('pager', currentPage)
      this.getPageList(this.page)
    },
    async handleSizeChange(pageSize) {
      this.limit = pageSize
      this.getPageList(this.page)
    },
    showDialog() {
      this.dialogFormVisible = true
      this.tmForm = { logoUrl: '', tmName: '' }
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 图片上传之前
    beforeAvatarUpload(file) {
      // 设置图片格式
      const isPNG = file.type === 'image/png'
      // 设置图片大小
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPNG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    },
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data
    },
    addOrUpdate() {
      this.$refs.ruleTmForm.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false
          let res = await this.$API.TradeMark.addOrUpdateTradeMark(this.tmForm)
          if (res.code === 200) {
            this.$message({ message: this.tmForm.id ? '修改成功!' : '添加成功!', type: 'success' })
            this.getPageList(this.tmForm.id ? this.page : 1)
          } else {
            this.$message({ message: '操作失败', type: 'error' })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 修改按钮
    updateTradeMark(row) {
      this.dialogFormVisible = true
      // 这里应当使用浅拷贝
      this.tmForm = { ...row }
    },
    deleteTradeMark(row) {
      this.$confirm(`是否确定删除${row.tmName}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await this.$API.TradeMark.deleteTradeMark(row.id)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          }
          this.getPageList(this.list.length > 1 ? this.page : this.page - 1)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>